import React from "react";

class AppClass extends React.Component {
    state = {
        obj: {
            name: "传智播客",
            address: {
                name: "南京校区",
            },
        },
        arr: [
            {
                name: "杭州校区",
            },
            {
                name: "厦门校区",
            },
            {
                name: "上海校区",
            },
            {
                name: "厦门校区",
            },
            {
                name: "厦门校区",
            },
        ],
    };

    render() {
        return (
            <div>
                <p>{this.state.obj.name}</p>
                <p>{this.state.obj.address.name}</p>
                {this.state.arr.map((item, index) => (
                    <div key={index}>{item.name}</div>
                ))}
                <button
                    onClick={() => {
                        // 改对象先深拷贝再修改属性值
                        let newObj = { ...this.state.obj };
                        newObj.address.name = "长沙校区";
                        this.setState({
                            obj: newObj,
                        });
                    }}>
                    修改对象
                </button>
                <button
                    onClick={() => {
                        // 改数组使用map修改
                        // 也可以用深拷贝再修改(前提需要知道需要修改的索引值)
                        const arr = this.state.arr.map((item) => {
                            if (item.name === "厦门校区") {
                                item.name = "北京校区";
                            }
                            return item;
                        });
                        this.setState({
                            arr,
                        });
                    }}>
                    修改数组
                </button>
            </div>
        );
    }
}

export default AppClass;
